const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const url = require("url");
const serverObj = http.createServer((req,res)=>{
    const urlObj = url.parse(req.url);
    if(urlObj.pathname.includes("/api")){
        dataHandle(req, res);
    }else{
        staticHandle(req, res);
    }
})
serverObj.listen(3000,()=>{
    console.log("服务器开启成功: http://localhost:3000");
})
function dataHandle(req, res){
    console.log(req.method);
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        fn(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end",()=>{
            const obj = qs.parse(str);
            fn(req, res, obj);
        })
    }
}
function fn(req, res, reqData){
    switch(reqData.type){
        case "getGoods":
            getGoods(req, res, reqData);
            break;
    }
}

function getGoods(req, res, reqData){
    fs.readFile("./databases/goods.json",(err,data)=>{
        if(err){
            res.write("not data")
        }else{
            res.write(data)
        }
        res.end();
    })
}

function staticHandle(req, res){
    const urlObj = url.parse(req.url);
    fs.readFile("./www" + urlObj.pathname, (err, data)=>{
        if(err){
            res.write("notFound");
        }else{
            res.write(data);
        }
        res.end();
    })
}